package info.emamian.droplet.web.controllers;

import info.emamian.droplet.data.DynamoDbClientFactory;
import info.emamian.droplet.data.DynamoDbSms;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(HomeController.class);

	// private final DynamoDBMapper dbMapper =
	// DynamoDbClientFactory.getDBMapperInstance();

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(final Locale locale, final Model model) {
		LOGGER.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
				DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);

		return "home";
	}

	@RequestMapping(value = "/load", method = RequestMethod.GET)
	public @ResponseBody
	String load(final HttpServletRequest request,
			@RequestParam(value = "id") final String id) {
		DynamoDBMapper mp = new DynamoDBMapper(
				DynamoDbClientFactory.getClientInstance());
		DynamoDbSms sms = mp.load(DynamoDbSms.class, id);
		return sms.toString();
	}

	@RequestMapping(value = "/check", method = RequestMethod.GET)
	public @ResponseBody
	String load() {
		return "ok";
	}

}
